package com.gravata.enigma.reader;

import android.content.Context;

import com.gravata.enigma.FtpHelper;
import com.gravata.enigma.PublishMessage;
import com.gravata.enigma.R;
import com.gravata.enigma.Utils;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.model.Bouquet;
import com.gravata.enigma.model.BouquetService;
import com.gravata.enigma.model.Service;

public class ParseFavoritos {
	private static String ENIGMA2_FOLDER="/etc/enigma2";
	private static PublishMessage listener;

	public static void parse(Context context,PublishMessage listener){
		ParseFavoritos.listener=listener;

		FtpHelper ftpHelper=new FtpHelper(context);

		try {
			ftpHelper.connect();
		} catch (Exception e1) {
			listener.publish(context.getString(R.string.ftp_error_conexao));
			try {
				Thread.sleep(4000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return ;
		}

		try{
			ParseFavoritos.listener.publish(context.getString(R.string.parse_favoritos_processando));

			TelaInicial.repositorioBouquets.excluir(TelaInicial.repositorioBouquets.listar(TelaInicial.profile));

			int ordem=1;
			String fileStr=ftpHelper.getFileString(ENIGMA2_FOLDER+"/bouquets.tv");
			String [] bouquetsMatchs=fileStr.split("\n");
			for(int a=1;a<bouquetsMatchs.length;a++){
				String bouquetReference=bouquetsMatchs[a];
				String fileName=Utils.getUserBouquet(bouquetReference);

				String [] userBouquets=ftpHelper.getFileString(ENIGMA2_FOLDER+"/"+fileName).split("\n");
				Bouquet bouquet=new Bouquet();
				bouquet.setReference(bouquetReference.trim());
				bouquet.setProfile(TelaInicial.profile);
				for(int i=0;i<userBouquets.length;i++){
					if(i==0){
						String nome=userBouquets[i].replaceAll("#NAME" , "").trim();
						bouquet.setName(nome);
						bouquet.setOrdem(ordem);

						TelaInicial.repositorioBouquets.inserir(bouquet);
					}else{
						String serviceReference=userBouquets[i].trim();

						Service service= TelaInicial.repositorioService.obterPorReference(serviceReference);
						if(service!=null){
							BouquetService bs=new BouquetService(bouquet, service, i+1);
							TelaInicial.repositorioBouquetService.inserir(bs);
						}
					}

				}
				ordem++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

        ftpHelper.disconnect();
	}
}
